﻿Imports CoreFX
Imports System
Imports ChatEngine
Imports System.Threading
Imports CoreFX.AppDomains.Communication
Imports Microsoft.VisualBasic.Compatibility
Namespace AppDomains
    Public Class ConnectionWorker
        Inherits MarshalByRefObject
        Dim textC As New System.Text.UTF8Encoding
        Dim toConvert() As Byte
        Private servar As ChatEngine.ServerManagement.Server
        Dim Path As String = VB6.GetPath()
        Dim adClient As ChatEngine.Client.IRCClient
        Dim adChanWin As ADIChannelWindow
        Dim adCommClient As RemotingClient
        Public Sub New()
            adCommClient = New RemotingClient
            adChanWin = New ADIChannelWindow(adCommClient)
        End Sub
        Public Sub InitLogging()
        End Sub
        Public Sub ConnectToServer(ByVal Server As ChatEngine.ServerManagement.Server, ByVal ChanWin As ChatEngine.Client.IChannelWindow)
            SharedVars.GlobalChannelWindow = adChanWin
            adClient = New ChatEngine.Client.IRCClient
            If adCommClient.StartClient(AppDomain.CurrentDomain.FriendlyName) = True Then
                '  adCommServer.StartServer(AppDomain.CurrentDomain.FriendlyName)
                AddHandler adClient.Connected, AddressOf adChatConnected
                AddHandler adClient.NewChannel, AddressOf adChatNewChan
                AddHandler adClient.AddLineToConsole, AddressOf adChatConsLine
                Dim t As Thread = New Thread(AddressOf StartConnection)
                servar = Server
                t.Start(Server.address & "|" & Server.port)
            Else
                Throw New Exception("Unable to establish communcation with the Chat Engine")
            End If
        End Sub
        Private Sub StartConnection(ByVal address As String)
            Dim addy As String()
            addy = address.Split(New Char() {"|"})
            adClient.ConnectToServer(addy(0), addy(1))
        End Sub
        Private Sub adChatConsLine(ByVal Info As String)
            adCommClient.AddConsoleLine(Info)
        End Sub
        Private Sub adChatNewChan(ByVal ChannelName As String, ByVal ChannelObj As ChatEngine.Client.Channel.IRCChannel)
            adCommClient.NewChannel(ChannelName, AppDomain.CurrentDomain.FriendlyName, ChannelObj)
            'MsgBox(ChannelName)
        End Sub
        Private Sub adChatConnected()
            Dim b As String
            toConvert = Convert.FromBase64String(servar.password)
            b = textC.GetString(toConvert)
            adClient.Login(servar.username, b, servar.username)
        End Sub
    End Class
End Namespace